import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
router.beforeEach(async (to, from, next) => {
	// start progress bar
	NProgress.start()
	// set page title
	document.title = to.meta.title || '野人体育赛事'
	// determine whether the user has logged in
	const hasToken = getToken()
	if (hasToken) {
		if (to.path === '/login') {
			next({ path: '/' })
			NProgress.done()
		} else {
			// 异步获取store中的路由
			const permission_routes = store.getters.permission_routes
			const hasRouters = permission_routes && permission_routes.length > 0
			// 判断store中是否有路由，若有，进行下一步
			if (hasRouters) {
				const matched = permission_routes.filter(route => {
					return (route.path != '/' && to.path.indexOf(route.path) > -1) ||
						(route.redirect && route.redirect === to.path)
				})
				if (to.path === '/noRedirect') {
					next('/404')
				} else if (!matched.length) {
					next('/401')
				} else {
					next()
				}
			} else {
				// store中没有路由，则需要获取获取异步路由，并进行格式化处理
				try {
					const role = store.getters.userInfo.admin_id === 1 ? ['admin', 'sponsor'] : ['sponsor']
					const accessRoutes = await store.dispatch('permission/getRoutes', role)
					router.addRoutes(accessRoutes)
					next({
						...to,
						replace: true
					})
				} catch (error) {
					next(`/login`)
					NProgress.done()
				}
			}
		}
	} else {
		/* has no token*/
		if (whiteList.indexOf(to.path) !== -1) {
			next()
		} else {
			// other pages that do not have permission to access are redirected to the login page.
			next(`/login`)
			NProgress.done()
		}
	}
})
router.afterEach(() => {
	NProgress.done()
})